package com.oneday.nuo.base.security.password;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


/**
 * 自定义的密码加密方法
 * @Author: liushuai
 * @Date: 2021/2/7 22:28
 * @param : * @param null
 * @return :
 **/
@Slf4j
@Component
public class NuoPasswordEncoder implements PasswordEncoder {
    public static final String  DEFAUTL_PASSWORD = "123456";

    /**
     * 对密码进行加密
     * @Author: liushuai
     * @Date: 2021/2/7 22:57
     * @param : * @param charSequence
     * @return :java.lang.String
     **/
    @Override
    public String encode(CharSequence charSequence) {
        // 加盐字符串
        String salt = BCrypt.gensalt();
        //加密过后的密码
        String passWord = BCrypt.hashpw((String) charSequence, salt);
        return passWord;
    }
    /**
     *  密码校验
     * @Author: liushuai
     * @Date: 2021/2/7 23:05
     * @param : * @param userPassWord 用户传过来的原密码
     * @param saltPassWord  数据库保存的密码
     * @return :boolean
     **/
    @Override
    public boolean matches(CharSequence userPassWord, String saltPassWord) {
        if(StrUtil.isBlank(saltPassWord)){
          log.error("加盐密码为空或包含空字符串");
          return false;
        }
        if(StrUtil.isBlank(userPassWord)){
            log.error("密码为空或密码存在空字符");
            return false;
        }
        boolean checkpw = BCrypt.checkpw(userPassWord.toString(), saltPassWord);
        return checkpw;

    }
}
